package se.hiq.wineo.client.widgets;

import se.hiq.wineo.client.events.WineListLoadedEvent;
import se.hiq.wineo.client.events.WineListLoadedEventHandler;
import se.hiq.wineo.client.widgets.common.ValueWidget;
import se.hiq.wineo.shared.data.WineDescriptor;

import com.google.gwt.event.shared.HandlerManager;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.Label;

/**
 * This widget presents statistics on all wines available
 * 
 * @author joakimsah
 *
 */
public class WineStatWidget extends Composite {

	// Widgets in this Composite
	private Grid mainPanel;
	private Label headingLabel;
	private ValueWidget totWines;
	private ValueWidget redWines;
	private ValueWidget whiteWines;
	private ValueWidget roseWines;
	
	private final HandlerManager eventBus;
	
	public WineStatWidget(HandlerManager eventBus) {
		this.eventBus = eventBus;
		
		mainPanel = new Grid(1, 5);
		mainPanel.setStyleName("wineStatWidget");
		
		headingLabel = new Label("Statistik");
		headingLabel.setStyleName("statistikHeading");
		totWines = new ValueWidget("# Viner:", "");
		redWines = new ValueWidget("# Röda:", "");
		whiteWines = new ValueWidget("# Vita:", "");
		roseWines = new ValueWidget("# Rosé:", "");
		
		mainPanel.setWidget(0, 0, headingLabel);
		mainPanel.setWidget(0, 1, totWines);
		mainPanel.setWidget(0, 2, redWines);
		mainPanel.setWidget(0, 3, whiteWines);
		mainPanel.setWidget(0, 4, roseWines);
		initWidget(mainPanel);
		
		initHandlers();
	}
	
	// ----- Public methods -----
	
	/**
	 * Update this widget with a list of the available wines. Used for generating statistics information.
	 * 
	 * @param winesArr List of available wines
	 */
	public void onCompleteWineList(WineDescriptor[] winesArr) {
		int noRed = 0;
		int noRose = 0;
		int noWhite = 0;
		for (WineDescriptor wd : winesArr) {
			switch (wd.getColor()) {
			case RED: 	noRed++; 	break;
			case ROSE: 	noRose++; 	break;
			case WHITE: noWhite++; 	break;
			}
		}
		totWines.setValue(Integer.toString(winesArr.length));
		redWines.setValue(Integer.toString(noRed));
		roseWines.setValue(Integer.toString(noRose));
		whiteWines.setValue(Integer.toString(noWhite));
	}
	
	// ----- Private methods -----
	
	private void initHandlers() {
		eventBus.addHandler(WineListLoadedEvent.TYPE, new WineListLoadedEventHandler() {
			@Override
			public void onWineListLoadedEvent(WineDescriptor[] descriptors) {
				onCompleteWineList(descriptors);
			}
		});
	}
	
	
}
